package com.ruoyi.wechat.handler;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.wechat.domain.OnlineService;
import com.ruoyi.wechat.service.impl.OnlineServiceServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {


    private static final Logger log = LoggerFactory.getLogger(ChatWebSocketHandler.class);

    private static final ConcurrentHashMap<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();
    private static final CopyOnWriteArraySet<WebSocketSession> customerServiceSessions = new CopyOnWriteArraySet<>();

    @Autowired
    private OnlineServiceServiceImpl onlineServiceService;

    @Autowired
    private TokenService tokenService;

    @Value("${wechart.wxUserRole}")
    private String wxUserRole;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String token = getTokenFromSession(session);
        String userId = getUserIdFromSession(session);
        LoginUser loginUser = tokenService.getLoginUser(token);

        if (Long.valueOf(wxUserRole) == loginUser.getUser().getRoleId()) {
            assignCustomerService(userId, session);
        } else {
            customerServiceSessions.add(session);
        }
        userSessions.put(userId, session);
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        String targetUserId = getTargetUserIdFromPayload(payload);
        if(targetUserId != null && targetUserId.length() > 0) {
            payload = payload.substring(targetUserId.length() + 1);
        }
        String token = getTokenFromSession(session);
        LoginUser loginUser = tokenService.getLoginUser(token);

        // 获取发送者信息
        String senderUserId = getUserIdFromSession(session);
        String senderUserName = loginUser.getUser().getUserName();

        log.debug("发送者id: " + senderUserId);
        log.debug("发送者角色id: " + loginUser.getUser().getRoleId());
        log.debug("目标用户id: " + targetUserId);
        log.debug("消息内容: " + payload);
        if (Long.valueOf(wxUserRole) == loginUser.getUser().getRoleId()) {
            WebSocketSession targetSession = userSessions.get(targetUserId);
            if (targetSession == null) {
                targetSession = assignCustomerService(senderUserId, session);
            }
            saveMessageOffline(senderUserId, targetUserId, payload);
            if (targetSession != null && targetSession.isOpen()) {
                targetSession.sendMessage(buildMessage(senderUserId, senderUserName, payload));
            } else {
                session.sendMessage(buildMessage("null", "客服", "暂无客服在线，消息已保存。"));
            }
        } else {
            WebSocketSession targetSession = userSessions.get(targetUserId);
            saveMessageOffline(senderUserId, targetUserId, payload);
            if (targetSession != null && targetSession.isOpen()) {
                targetSession.sendMessage(buildMessage(senderUserId, senderUserName, payload));
            } else {
                session.sendMessage(buildMessage(targetUserId, "用户", "用户已离线，消息已保存。"));
            }
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {

            String userId = getUserIdFromSession(session);
            userSessions.remove(userId);
            customerServiceSessions.remove(session);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 循环遍历移除userSessions和customerServiceSessions已关闭的session
            for (String key : userSessions.keySet()) {
                WebSocketSession webSocketSession = userSessions.get(key);
                if (!webSocketSession.isOpen()) {
                    userSessions.remove(key);
                }
            }
            for (WebSocketSession webSocketSession : customerServiceSessions) {
                if (!webSocketSession.isOpen()) {
                    customerServiceSessions.remove(webSocketSession);
                }
            }
        }
    }

    private WebSocketSession assignCustomerService(String userId, WebSocketSession session) throws Exception {
        WebSocketSession customerServiceSession = null;
        if (customerServiceSessions.isEmpty()) {
            session.sendMessage(new TextMessage("没有在线客服，稍后再试。"));
            session.sendMessage(buildMessage("null", "客服", "没有在线客服，稍后再试。"));
        } else {
            customerServiceSession = customerServiceSessions.iterator().next();
            String userid = getUserIdFromSession(customerServiceSession);
            session.sendMessage(buildMessage(userid, "客服", "很高兴为您服务"));
            customerServiceSession.sendMessage(buildMessage(userId,"用户","新用户已连接"));
        }
        return customerServiceSession;
    }

    private void saveMessageOffline(String senderUserId, String receiverUserId, String content) {
        OnlineService onlineService = new OnlineService();
        onlineService.setContent(content);
        onlineService.setSenderId(senderUserId);
        onlineService.setReceiverId(receiverUserId);
        onlineService.setState("0");
        onlineServiceService.insertOnlineService(onlineService);
    }

    private String getUserIdFromSession(WebSocketSession session) {
        // 从 session 中获取用户ID的逻辑
        String token = getTokenFromSession(session);
        LoginUser loginUser = tokenService.getLoginUser(token);
        String userId = "";


        if (Long.valueOf(wxUserRole) == loginUser.getUser().getRoleId()) {
            userId = loginUser.getUser().getNickName().toString();
        } else {
            userId = loginUser.getUser().getUserId().toString();
        }
        return userId;
    }

    private String getTokenFromSession(WebSocketSession session) {
        // 从 session 中获取用户Token的逻辑
        String token = session.getUri().getQuery().split("=")[1];
        token = token.replace(Constants.TOKEN_PREFIX, "");
        return token;
    }

    private String getTargetUserIdFromPayload(String payload) {
        // 从消息内容中提取目标用户ID的逻辑
        return payload.split(":")[0];
    }
    // 拼接发送的消息
    private TextMessage buildMessage(String senderUserId, String senderUserName, String payload) {
        return new TextMessage(senderUserId + ":" + senderUserName + ":" + payload);
    }
}